package com.ttmusic.fragments.maintab;


import java.util.List;

import com.ttmusic.activitys.MainActivity;
import com.ttmusic.activitys.R;
import com.ttmusic.core.MusicManager;
import com.ttmusic.entity.AbstractMusic;
import com.ttmusic.entity.MusicInfo;
import com.ttmusic.view.LetterBar;
import com.ttmusic.view.adapters.MusicAdapter;
import com.ttmusic.view.adapters.MusicAdapter.SortType;
import com.ttmusic.view.listeners.OnItemClickListener;
import com.ttmusic.view.listeners.OnTouchingLetterChangedListener;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AbsListView;

public class LocalMusicFragment extends ListFragment implements OnClickListener {
	
	private View view;
	private LayoutInflater inflater;
	private boolean isABC = true;  //是否显示Letterbar视图
	private LetterBar letterBar;
	private TextView dialog;
	private ListView local_song;//, local_artist, local_album
	private MusicAdapter musicAdapter;
  	//播放列表
  	private List<AbstractMusic> musicInfoList;
  	//ListView的footerView和headerView里面的歌曲数量
  	private TextView tv_listview_itemcount;

	public LocalMusicFragment(List<AbstractMusic> musicInfoList) {
		this.musicInfoList = musicInfoList;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		this.inflater = inflater;
		view = inflater.inflate(R.layout.fragment_localmusic, container, false);
		return view;
	}

	@SuppressLint("HandlerLeak")
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		System.out.println("LocalMusicFragment创建了~~~~~~~~~~~~~~~~~~~~~~~~~");
		//字母快速检索工具栏
		letterBar = (LetterBar)view.findViewById(R.id.letterBar);
		dialog = (TextView)view.findViewById(R.id.dialog);
		local_song = this.getListView();
		
        musicAdapter = new MusicAdapter(getActivity(), musicInfoList, isABC);
		this.showLetterBar();
		this.initView();
		this.showMusicList();
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			default:
				break;
		}
	}
	
	/**
	 * 展示歌曲列表
	 */
	@SuppressLint("InflateParams")
	private void showMusicList() {
		View header = inflater.inflate(R.layout.listheader_footer_item_count, null);
        tv_listview_itemcount = (TextView) header.findViewById(R.id.tv_listview_itemcount);
        tv_listview_itemcount.setText(musicInfoList.size() + " 首歌曲");
        local_song.addHeaderView(header);
        local_song.addFooterView(header);
        //自定义的listener 简化了android ListView自带的OnItemClickListener复杂的参数
        musicAdapter.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(int position) {
				if(MusicManager.getPlayingList() != musicInfoList) {
					//播放音乐时判断当前点击的音乐所在list是不是当前播放列表  若不是，则切换播放列表为当前fragment的musicInfoList
			        MusicManager.setPlayingList(musicInfoList);
				}
				if(position != MusicManager.getNowPlayingIndex()) {
					//准备和播放
					MainActivity.adapterCurrentPlay = musicAdapter;
			        MainActivity.mManager.prepareAndPlay(position);
				}
			}
		});
        local_song.setAdapter(musicAdapter);
        MainActivity.adapterCurrentShow = musicAdapter;
    }
	
	
	/**
	 * 展示字母快速检索工具栏
	 */
	private void showLetterBar() {
        if (isABC) {
        	letterBar.setTextView(dialog);
        	letterBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {
				@Override
				public void onTouchingLetterChanged(String letter) {
					int position = musicAdapter.getPositionForSection(letter.charAt(0));
                    if (position != -1) {
                    	local_song.setSelection(position);
                    }
				}
			});
        	letterBar.setVisibility(View.VISIBLE);
        } else {
        	letterBar.setVisibility(View.INVISIBLE);
    	}
	}
	
	private void initView() {
        if (isABC) {
        	local_song.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                    if (view.getCount() != 0) {
                    	//滚动时显示
                        if (scrollState != AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                            dialog.setVisibility(View.VISIBLE);
                        } else {
                        //不滚动时隐藏
                        	local_song.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    dialog.setVisibility(View.GONE);
                                }
                            }, 100);
                        }
                    }
                }
                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    MusicInfo musicInfo = (MusicInfo) local_song.getItemAtPosition(firstVisibleItem);
                    if (dialog != null && musicInfo != null) {
                    	SortType type = MusicAdapter.getSortType();
                    	String dialogStr = "#";
                        if(type == SortType.SORT_BY_ADDTIME) {
                    		
                    		//添加时间还没获取到，要先做扫描，将歌曲信息保存到SQLite数据库中 增加一个添加时间字段
                    	}else if(type == SortType.SORT_BY_ARTIST) {
                    		dialogStr = musicInfo.getPinYinHeadCharofArtist();
                    	}else if(type == SortType.SORT_BY_ALBUM) {
                    		dialogStr = musicInfo.getPinYinHeadCharofAlbum();
                    	}else {
                    		dialogStr = musicInfo.getPinYinHeadCharofTitle();
                    	}
                        dialog.setText(dialogStr.charAt(0)+"");
                    }
                }
            });
        }
    }


	/**
	 * 本fragment显示和隐藏监听
	 */
	@Override
	public void onHiddenChanged(boolean ishidden) {
		if(!ishidden) {
			MainActivity.adapterCurrentShow = musicAdapter;
			if(MainActivity.adapterCurrentPlay == musicAdapter) {
				//切换到当前fragment时 自动滚动到当前播放的音乐位置处
				//带滚动效果 滚动到指定索引处 由于添加了headerView 所以要+1
		        local_song.smoothScrollToPosition(MusicManager.getNowPlayingIndex()+1);
			}
		}
	}

	/**
	 * 本地歌曲列表发生了改变
	 */
	public void changeData(List<AbstractMusic> musicInfoList) {
		musicAdapter.changeData(musicInfoList);
		tv_listview_itemcount.setText(musicInfoList.size() + " 首歌曲");
	}
	
}
